package com.hunantv.mglive.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.PopupWindow;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.Constant;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.GiftingInfoModel;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.common.EncodeData;
import com.hunantv.mglive.widget.AdvertGlodDialog;
import com.hunantv.mglive.widget.GlodDialog;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by qiuda on 16/2/22.
 */
public class PromoteGoldUtil implements HttpUtils.callBack {
    private static final int SHOW_WINDOW_DELAY = 5000;                  //进入界面延迟显示随机金币的时间
    private static final int WINDOW_DISPLAY_TIME = 10000;               //随机金币显示的时长
    private static final int NORMAL_GET_DATA_TIME = 60000;              //默认轮训时间
    private static GiftingInfoModel mGifttingModel;                     //静态存储获取到的随机金币对象
    private static long mNextDisplayTime;                               //下一次显示随机金币的时间（上次显示后，用户没有点击领取）

    private final int WHAT_DISMISS_WINDOW = 0;           //  x秒之后隐藏随机金币
    private final int WHAT_WINDOW_SHOW = 1;             //显示随机金币
    private final int WHAT_WINDOW_NEXT = 2;             //调用随机金币的查询接口

    private HttpUtils mHttp;
    private boolean mIsGettingInfo;
    private boolean mIsGetGold;
    private boolean mIsDisplay;                         //是否显示随机金币（根据onResum  为true 和onPause 为false）

    private Context mContext;
    private GlodDialog mGlodDialog;
    private PopupWindow mPopupWindow;

    private AdvertGlodDialog mAdvertGlodDialog;

    private Handler mHandler;


    /**
     * 构造方法
     *
     * @param context 传入context
     *                根据context 的路径判断是否过来不显示随机金币
     */

    public PromoteGoldUtil(Context context) {
        String activityName = "";
        if (context != null) {
            activityName = context.toString();
        }
        //过滤 WebViewActivity、 登录相关、Dialog相关、用户模块界面的随机金币显示
        if (!activityName.contains("WebViewActivity") && !activityName.contains("Login") && !activityName.contains("Dialog") && !activityName.contains("StartActivity") && !activityName.contains(".user.")) {
            mContext = context;
            mGlodDialog = new GlodDialog(context);
            mAdvertGlodDialog = new AdvertGlodDialog(context);
            mHttp = new HttpUtils(MaxApplication.getAppContext(), this);
            initHandler();
        }
    }

    /**
     * 初始化Handler
     */
    private void initHandler() {
        mHandler = new Handler() {
            @Override
            public void dispatchMessage(Message msg) {
                super.dispatchMessage(msg);
                switch (msg.what) {
                    case WHAT_DISMISS_WINDOW://隐藏随机金币提示框，确定下一次的显示时间，并且发送延迟消息，延迟nextTime时间显示
                        try {
                            if (mPopupWindow != null && mPopupWindow.isShowing()) {
                                mPopupWindow.dismiss();
                            }
                            long mNextTime = 60 * 1000;
                            if (mGifttingModel != null) {
                                mNextTime = Long.parseLong(mGifttingModel.getNextTime()) * 1000;
                            }
                            mNextDisplayTime = System.currentTimeMillis() + mNextTime;
                            mGifttingModel = null;
                            getNextData(mNextTime);//取消显示后，根据下次提示的时间重新获取随机金币对象（随机金币对象的令牌有失效时间，所以显示后，如果不点击，自动消失后，丢弃对象）
                        } catch (Exception e) {
                        }
                        break;
                    case WHAT_WINDOW_SHOW://根据mIsDisplay  判断界面是否onResum，查询是的uid是否等于当前uid，当前时间是否大于等于设置的下次显示时间
                        if (mIsDisplay) {
                            if (mGifttingModel != null) {
                                startGfitingView(mGifttingModel);
                            }
                        }
                        break;
                    case WHAT_WINDOW_NEXT://查询随机金币的数据
                        startGetGifttingInfo();
                        break;
                }
            }
        };
    }

    /**
     * 显示随机金币的提示框
     *
     * @param model 随机金币对象
     * @return 是否成功显示
     */
    private boolean startGfitingView(GiftingInfoModel model) {
        if ((mPopupWindow != null && mPopupWindow.isShowing())) {
            return false;
        }
        View view = ((Activity) mContext).getWindow().getDecorView();
        View viewWindow = LayoutInflater.from(mContext).inflate(R.layout.have_gift_layout, null);
        ImageButton imageButton = (ImageButton) viewWindow.findViewById(R.id.ibtn_gold_window_input);
        if (com.bumptech.glide.util.Util.isOnMainThread() && mContext != null && !((Activity) mContext).isFinishing()) {
            Glide.with(mContext).load(model.getImage()).centerCrop().into(imageButton);
        }
        mPopupWindow = new PopupWindow(viewWindow, FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(false);
        mPopupWindow.setOutsideTouchable(false);

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!MaxApplication.getApp().isLogin() &&
                        !((Activity) mContext).isFinishing()) {//点击后，判断当前是否登录，未登录跳转登录页面
                    MGTVUtil.getInstance().login(MaxApplication.getAppContext());
                } else if (mGifttingModel != null && !StringUtil.isNullorEmpty(mGifttingModel.getCoinInfo())) {//登录后，金币不为空，查询随机金币的具体信息
                    startGetGifting(mGifttingModel.getTicket());
                }
                mHandler.removeMessages(WHAT_DISMISS_WINDOW);//移除取消随机金币提示框的延迟消息
                mPopupWindow.dismiss();
            }
        });
        try {
            DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
            int mWidth = dm.widthPixels;
            int mHeight = dm.heightPixels;
            if (mContext == null || ((Activity) mContext).isFinishing()) {
                return false;
            }
            mPopupWindow.showAtLocation(view, Gravity.NO_GRAVITY, mWidth, (int) (mHeight - UIUtil.dip2px(mContext, 200)));
            mHandler.sendEmptyMessageDelayed(WHAT_DISMISS_WINDOW, WINDOW_DISPLAY_TIME);
        } catch (Exception ignored) {

        }
        return true;
    }

    /**
     * 影藏金币弹窗
     */
    public void hideGfitView(){
        if(mPopupWindow!=null && mPopupWindow.isShowing()){
            mHandler.removeMessages(WHAT_DISMISS_WINDOW);//移除取消随机金币提示框的延迟消息
            mPopupWindow.dismiss();
        }
    }

    /**
     * 界面的onResum方法执行
     * 判断全局的 随机金币对象是否存在，为空时调用查询随机金币的接口，不为空时延迟 5秒 进入显示随机金币的逻辑
     */
    public void regirsterActivity() {
        mIsDisplay = true;
        if (mContext != null) {
            mHandler.removeMessages(WHAT_DISMISS_WINDOW);
            mHandler.removeMessages(WHAT_WINDOW_SHOW);
            mHandler.removeMessages(WHAT_WINDOW_NEXT);
            long time = System.currentTimeMillis();
            if (time >= mNextDisplayTime) {
                getNextData(0);//超过了上次计算的下次显示时间，则获取新数据
            } else {
                getNextData(mNextDisplayTime - time);//未超过计算的下次显示时间，延迟获取数据
            }
        }

    }

    /**
     * 界面的onPause方法，移除所有查询、显示的消息，取消随机金币的显示
     */

    public void unRegirsterAcivity() {
        mIsDisplay = false;
        if (mContext != null) {
            long mNextTime = 60 * 1000;
            if (mGifttingModel != null) {
                mNextTime = Long.parseLong(mGifttingModel.getNextTime()) * 1000;
            }
            mNextDisplayTime = System.currentTimeMillis() + mNextTime;
            if (mPopupWindow != null && mPopupWindow.isShowing()) {
                mPopupWindow.dismiss();
            }
            mHandler.removeMessages(WHAT_DISMISS_WINDOW);
            mHandler.removeMessages(WHAT_WINDOW_SHOW);
            mHandler.removeMessages(WHAT_WINDOW_NEXT);
        }
    }

    /**
     * 查询随机金币的详细信息
     */
    private synchronized void startGetGifttingInfo() {
        if (mIsGettingInfo) {
            return;
        }
        mIsGettingInfo = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> param = new FormEncodingBuilderEx()
                        .add("uid", MaxApplication.getApp().getUid())
                        .add("token", MaxApplication.getApp().getToken())
                        .build();
                EncodeData data = MgEncodUtil.getEncodeHeader(param, MaxApplication.getApp().getSignFill0());
                if (data != null) {
                    Map<String, String> header = new HashMap<>();
                    header.put(Constant.REQEUST_HEADER_SIGN, data.getEncode().toUpperCase());
                    param.put("timestamp", data.getTime());
                    param.put("salt", data.getSalt());
                    mHttp.post(BuildConfig.URL_GET_GIFTING_INFO_V2, param, header);
                }
            }
        }).start();
    }

    /**
     * 领取随机金币
     */
    public synchronized void startGetGifting(final String ticket) {
        if (mIsGetGold) {
            return;
        }
        mIsGetGold = true;
        if (!StringUtil.isNullorEmpty(ticket)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Map<String, String> param = new FormEncodingBuilderEx()
                            .add("uid", MaxApplication.getApp().getUid())
                            .add("token", MaxApplication.getApp().getToken())
                            .add("ticket", ticket)
                            .build();
                    EncodeData data = MgEncodUtil.getEncodeHeader(param, MaxApplication.getApp().getSignFill0());
                    if (data != null) {
                        Map<String, String> header = new HashMap<>();
                        header.put(Constant.REQEUST_HEADER_SIGN, data.getEncode().toUpperCase());
                        param.put("timestamp", data.getTime());
                        param.put("salt", data.getSalt());
                        mHttp.post(BuildConfig.URL_GET_GIFTING_V2, param, header);
                    }
                }
            }).start();
        }
    }

    @Override
    public boolean get(String url, Map<String, String> param) {
        return mHttp.get(url, param);
    }

    @Override
    public boolean post(String url, Map<String, String> param) {
        return mHttp.post(url, param);
    }

    @Override
    public void onError(String url, Exception e) {

    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        if (BuildConfig.URL_GET_GIFTING_V2.contains(url)) {
            return JSON.parseObject(resultModel.getData(), GiftingInfoModel.class);
        } else if (BuildConfig.URL_GET_GIFTING_INFO_V2.equals(url)) {
            return JSON.parseObject(resultModel.getData(), GiftingInfoModel.class);
        }
        return null;
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {
        if (BuildConfig.URL_GET_GIFTING_V2.contains(url)) {
            mIsGetGold = false;
            if ("1203".equals(resultModel.getCode()) && !((Activity) mContext).isFinishing()) {//提示为绑定，跳转绑定界面
                //TODO MGTV
//                Intent intent = new Intent(mContext, BindMobileFirstDialogActivity.class);
//                mContext.startActivity(intent);
            } else {
                getNextData(NORMAL_GET_DATA_TIME);
            }
        } else if (BuildConfig.URL_GET_GIFTING_INFO_V2.equals(url)) {
            mIsGettingInfo = false;
            getNextData(NORMAL_GET_DATA_TIME);
        }

    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) {
        if (BuildConfig.URL_GET_GIFTING_V2.contains(url)) {
            mIsGetGold = false;
            if (resultModel.getDataModel() != null) {
                GiftingInfoModel gifttingInfoModel = (GiftingInfoModel) resultModel.getDataModel();
                String coinInfo = gifttingInfoModel.getCoinInfo();
                if (!StringUtil.isNullorEmpty(coinInfo) && mGifttingModel != null) {//显示领取成功提示框
                    if (GiftingInfoModel.TYPE_SURPRISE_BIG.equals(mGifttingModel.getType())) {
                        //大惊喜
                        mAdvertGlodDialog.creat().show(mGifttingModel);
                    } else if (GiftingInfoModel.TYPE_SURPRISE_SMALL.equals(mGifttingModel.getType())) {
                        //小惊喜
                        mGlodDialog.creat().show(mGifttingModel.getCoinInfo(), mGifttingModel.getSponsor());
                    }
                    mGifttingModel = null;
                    mNextDisplayTime = 0;
                }
                getNextData(gifttingInfoModel.getNextTime());//根据nextTime 查询下一次的随机金币
            }
        } else if (BuildConfig.URL_GET_GIFTING_INFO_V2.equals(url)) {
            mIsGettingInfo = false;
            GiftingInfoModel gifttingModel = (GiftingInfoModel) resultModel.getDataModel();
            if ("1".equals(gifttingModel.getIsActive())) {//活动是否有效
                if ("0".equals(gifttingModel.getRemainderTime()) || gifttingModel.getRemainderTime() == null) {//提示时间是否为0或者null，记录随机金币对象
                    mGifttingModel = gifttingModel;
                    mHandler.sendEmptyMessage(WHAT_WINDOW_SHOW);//发送显示随机金币的消息
                } else {
                    getNextData(gifttingModel.getRemainderTime());
                }
            } else {//活动无效情况，默认十分钟轮训随机金币查询接口
                getNextData(NORMAL_GET_DATA_TIME);
            }
        }
    }

    /**
     * 查询下一次随机金币接口
     *
     * @param nextTime 间隔时间
     */
    private void getNextData(String nextTime) {
        long mDelay = Long.parseLong(nextTime) * 1000;
        if (mDelay == -1) {
            mDelay = 1000 * 60 * 60;//-1表示已经领完
        }else if(mDelay < 0){
            mDelay = 1000 * 60 * 3;//小于0默认使用3分钟
        }
        getNextData(mDelay);
    }

    /**
     * 查询下一次随机金币接口
     *
     * @param nextTime 间隔时间
     */
    private void getNextData(long nextTime) {
        mHandler.sendEmptyMessageDelayed(WHAT_WINDOW_NEXT, nextTime);
    }


    public static void resetNextTime() {
        mNextDisplayTime = 0;
    }

}
